package com.atao.service.impl;

import cn.hutool.json.JSONUtil;
import com.atao.constants.SystemConstant;
import com.atao.domain.Result;
import com.atao.domain.entity.Author;
import com.atao.domain.entity.AuthorLocation;
import com.atao.mapper.AuthorMapper;
import com.atao.service.AuthorLocationService;
import com.atao.service.AuthorService;
import com.atao.utils.CurAuthentication;
import com.atao.utils.WebRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;

import static cn.hutool.poi.excel.sax.AttributeName.r;

/**
 * (Author)表服务实现类
 *
 * @author makejava
 * @since 2023-03-05 16:03:24
 */
@Service("authorService")
public class AuthorServiceImpl extends ServiceImpl<AuthorMapper, Author> implements AuthorService {

    @Autowired
    private AuthorLocationService authorLocationService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    private String handleInfo(String userInfo) {
        StringBuilder sb = new StringBuilder();
        for (char c : userInfo.toCharArray()) {
            if (c != ':' && c != '"' && c != '\n') {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    @Override
    public Result authorList() {
        return Result.ok(list());
    }

    @Override
    public Result getCurAuthor(String userInfo) {
        Author author;

        userInfo = handleInfo(userInfo);
        String redisKey = SystemConstant.ARTICLE_USER + userInfo;
        String redisInfo = redisTemplate.opsForValue().get(redisKey);
        if (redisInfo != null) {
            author = JSONUtil.toBean(redisInfo, Author.class);
            return Result.ok(author);
        }
        LambdaQueryWrapper<AuthorLocation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AuthorLocation::getLocation, userInfo);
        AuthorLocation authorLocation = authorLocationService.getOne(wrapper);
        if (authorLocation != null) {
            author = getById(authorLocation.getAuthor());
        } else {
            author = getById(SystemConstant.VISITOR_ID);
        }
        redisTemplate.opsForValue().set(redisKey, JSONUtil.toJsonStr(author));
        return Result.ok(author);
    }

    @Override
    public Result addAuthor(String location, String name) {

        boolean fake = false; // 检查是否是atao ataox为真
        if ("atao121333".equals(name)) {
            name = "atao";
        } else if ("atao".equals(name) || name.startsWith("atao") || name.contains("atao")) {
            fake = true;
        }

        location = handleInfo(location);

        LambdaQueryWrapper<Author> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Author::getName, name);
        Author author = getOne(wrapper);
        //不存在作者
        Integer authorId;
        if (author == null) {
            String img = WebRequest.sendGet(SystemConstant.AUTHOR_IMG_API, null);
            author = new Author(null, name, img, SystemConstant.AUTHOR_DEFAULT_DESCRIPTION);
            save(author);
            authorId = author.getId();
        } else {
            authorId = author.getId();
        }
        if (fake) {
            return Result.ok(author);
        }
        LambdaQueryWrapper<AuthorLocation> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(AuthorLocation::getLocation, location);
        int existLocation = authorLocationService.count(wrapper1);
        //不存在location
        if (existLocation == 0) {
            AuthorLocation al = null;
            if (authorId != null) {
                al = new AuthorLocation(null, location, authorId);
            }
            authorLocationService.save(al);
            redisTemplate.opsForValue().set(SystemConstant.ARTICLE_USER + location, JSONUtil.toJsonStr(author));
        }
        //如果location已经存在，则说明有两个人用了同一个机器，此时优先保护首次注册的location
        return Result.ok(author);
    }
}
